package com.madao.im.config.exception;

import com.madao.im.config.constant.ErrorCode;
import com.madao.im.response.JsonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * spring 全局异常处理
 *
 * @author chengjunchao
 * @version 1.0.0
 * @date 2021/12/6 16:05
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private String toErrorLog(String url, int status, String message) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n##################### [ ERROR START ] ####################\n");
        stringBuilder.append("URL: ").append(url).append("\n");
        stringBuilder.append("STATUS CODE: ").append(status).append("\n");
        stringBuilder.append("ERROR MESSAGE: ").append(message).append("\n");
        stringBuilder.append("##################### [ ERROR END ] ####################\n");
        return stringBuilder.toString();
    }

    @ExceptionHandler({BaseException.class})
    public ResponseEntity<Object> handlerBaseException(HttpServletRequest req, BaseException ex) {
        String uri = req.getRequestURI();
        String message = ErrorCode.getMsg(ErrorCode.ERROR_CODE_1001);
        log.error(this.toErrorLog(uri, ex.getCode(), message), ex);
        return JsonResponse.fail(ex.getCode());
    }

    @ExceptionHandler({Exception.class})
    public ResponseEntity<Object> handlerException(HttpServletRequest req, Exception ex) {
        String uri = req.getRequestURI();
        String message = ErrorCode.getMsg(ErrorCode.ERROR_CODE_1001);
        log.error(this.toErrorLog(uri, ErrorCode.ERROR_CODE_1001, message), ex);
        return JsonResponse.fail(ErrorCode.ERROR_CODE_1001);
    }

    @ExceptionHandler({Throwable.class})
    public ResponseEntity<Object> handlerThrowable(HttpServletRequest req, Throwable ex) {
        String uri = req.getRequestURI();
        String message = ErrorCode.getMsg(ErrorCode.ERROR_CODE_1001);
        log.error(this.toErrorLog(uri, ErrorCode.ERROR_CODE_1001, message), ex);
        return JsonResponse.fail(ErrorCode.ERROR_CODE_1001);
    }
}
